package com.jason.java.demo.socket;

import android.os.Bundle;
import android.util.Log;
import android.view.View;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.cby.code.util.ThreadPoolUtil;
import com.jason.java.demo.R;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter;
import java.net.InetAddress;
import java.net.Socket;

/**
 * @description: SocketClientActivity
 * @author: ChenBaoYang
 * @createDate: 2022/3/18 3:30 下午
 */
public class SocketClientActivity extends AppCompatActivity {

    private ConnectListener listener;


    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_socket_client);
        listener = new ConnectListener();
    }

    public void connectClick(View view) {
        ThreadPoolUtil.execute(listener);
    }


    static class ConnectListener implements Runnable{

        private Socket socket;
        private boolean connectionState = false;

        @Override
        public void run() {
            connect();
        }


        public void connect(){
            try{
                InetAddress inetAddress = InetAddress.getLocalHost();
                String ip = inetAddress.getHostAddress();
                socket = new Socket(ip,8888);
                Log.i("chenby","connect server ing");
                connectionState = true;
                OutputStreamWriter osw = new OutputStreamWriter(socket.getOutputStream(),"UTF-8");
                //ThreadPoolUtil.execute(new ClientListener(socket));
                //ThreadPoolUtil.execute(new ClientSend(this,socket,osw));
                //ThreadPoolUtil.execute(new ClientHeart(this, socket,osw));
            }catch (Exception e){
                connectionState = false;
            }
        }
        //自动重连机制
        public void reconnect(){
            while(!connectionState){
                Log.i("chenby","正在尝试重新连接.....");
                connect();
                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }

        public void sendData() {
            ThreadPoolUtil.execute(new ClientSend(this,socket));
        }
    }


    public void sendClick(View view) {

        listener.sendData();
    }



    static class ClientListener implements Runnable{

        public Socket socket;

        public ClientListener(Socket socket) {
            this.socket = socket;
        }

        @Override
        public void run() {
            try{
                InputStream is = socket.getInputStream();
                InputStreamReader isr = new InputStreamReader(is,"UTF-8");
                //专程BufferReader
                BufferedReader reader = new BufferedReader(isr);
                //获取数据转成字符串
                String info = null;
                while ((info = reader.readLine()) != null) {
                    //循环读取客户端的信息
                    Log.i("chenby","客户端发送过来的信息:" + info);
                }
                //关闭输入流
                socket.shutdownInput();



            }catch (Exception e){
                e.printStackTrace();
            }
        }
    }

    static class ClientSend implements Runnable{

        public Socket socket;
        private ConnectListener activity;

        public ClientSend(ConnectListener activity, Socket socket) {
            this.socket = socket;
            this.activity = activity;
        }

        @Override
        public void run() {
            try{

                InetAddress inetAddress = InetAddress.getLocalHost();
                String ip = inetAddress.getHostAddress();
                OutputStream os = socket.getOutputStream();
                InputStream is = socket.getInputStream();

                ObjectOutputStream oos = new ObjectOutputStream(os);
                ObjectInputStream ois = new ObjectInputStream(is);
//                for (int i = 0; i < 10; i++) {
//                    String req = "客户端：~" + ip + "~ 接入服务器！！";
//                    oos.writeObject(req);
//                    //获取数据转成字符串
//                    String res = (String) ois.readObject();
//                    Log.i("chenby","res = "+res);
//                }
                String req = "客户端：~" + ip + "~ 接入服务器！！";
                oos.writeObject(req);
                //获取数据转成字符串
                String res = (String) ois.readObject();
                Log.i("chenby","res = "+res);

                oos.flush();
                ois.close();

//                PrintWriter pw = new PrintWriter(os);
//                // 获取客户端的ip地址
//                InetAddress inetAddress = InetAddress.getLocalHost();
//                String ip = inetAddress.getHostAddress();
//                pw.write("客户端：~" + ip + "~ 接入服务器！！");
//                pw.flush();
//                pw.close();
            }catch (Exception e){
                e.printStackTrace();
                Log.i("chenby","client error = "+e.getMessage());
                try{
                    socket.close();
                    activity.connectionState = false;
                    activity.reconnect();

                }catch (Exception e2){
                    e2.printStackTrace();
                }
            }
        }
    }

    static class ClientHeart implements Runnable {

        private Socket socket;
        private OutputStreamWriter osw;

        private ConnectListener activity;

        public ClientHeart(ConnectListener activity, Socket socket,OutputStreamWriter osw){
            this.socket = socket;
            this.osw = osw;
            this.activity = activity;
        }

        @Override
        public void run() {
            try{
                Log.i("chenby","心跳包线程已启动");

                while(true){
                    Thread.sleep(5000);
                    osw.write("*****心跳包*****");
                    osw.flush();
                }
            }catch (Exception e){
                e.printStackTrace();
                try{
                    socket.close();
                    activity.connectionState = false;
                    activity.reconnect();

                }catch (Exception e2){
                    e2.printStackTrace();
                }
            }
        }
    }
}
